package com.coursehub.course.repository;

import com.coursehub.course.entity.Course;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 课程仓库接口
 * 
 * @author CourseHub Team
 */
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
    
    /**
     * 根据教师ID查找课程
     */
    List<Course> findByTeacherId(Long teacherId);
    
    /**
     * 根据教师ID分页查找课程
     */
    Page<Course> findByTeacherId(Long teacherId, Pageable pageable);
    
    /**
     * 根据课程状态查找课程
     */
    List<Course> findByStatus(Course.CourseStatus status);
    
    /**
     * 根据课程状态分页查找课程
     */
    Page<Course> findByStatus(Course.CourseStatus status, Pageable pageable);
    
    /**
     * 根据课程代码查找课程
     */
    Optional<Course> findByCourseCode(String courseCode);
    
    /**
     * 根据课程名称模糊查询
     */
    @Query("SELECT c FROM Course c WHERE c.name LIKE %:name%")
    List<Course> findByNameContaining(@Param("name") String name);
    
    /**
     * 根据课程名称模糊查询（分页）
     */
    @Query("SELECT c FROM Course c WHERE c.name LIKE %:name%")
    Page<Course> findByNameContaining(@Param("name") String name, Pageable pageable);
    
    /**
     * 查找已发布的课程
     */
    @Query("SELECT c FROM Course c WHERE c.status = 'PUBLISHED' OR c.status = 'ONGOING'")
    List<Course> findPublishedCourses();
    
    /**
     * 查找已发布的课程（分页）
     */
    @Query("SELECT c FROM Course c WHERE c.status = 'PUBLISHED' OR c.status = 'ONGOING'")
    Page<Course> findPublishedCourses(Pageable pageable);
    
    /**
     * 根据教师ID和课程状态查找课程
     */
    List<Course> findByTeacherIdAndStatus(Long teacherId, Course.CourseStatus status);
    
    /**
     * 统计教师的课程数量
     */
    @Query("SELECT COUNT(c) FROM Course c WHERE c.teacherId = :teacherId")
    Long countByTeacherId(@Param("teacherId") Long teacherId);
    
    /**
     * 统计某状态的课程数量
     */
    Long countByStatus(Course.CourseStatus status);
    
    /**
     * 检查课程代码是否存在
     */
    boolean existsByCourseCode(String courseCode);
    
    /**
     * 检查教师是否有指定名称的课程
     */
    boolean existsByTeacherIdAndName(Long teacherId, String name);
}